package ch.kerbtier.webglue;

import java.io.IOException;

import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class GlueContextListener implements ServletContextListener{

	public void contextDestroyed(ServletContextEvent sce) {
		final GroovyScriptEngine engine = (GroovyScriptEngine)sce.getServletContext().getAttribute("glue_groovy_engine");
        final Binding binding = new Binding();
        
        binding.setVariable("servletContext", sce.getServletContext());
        binding.setVariable("context", sce.getServletContext());

        binding.setVariable("script", new Object() {
			public Object evaluate(String name) {
				try {
					return engine.run(name, binding);
				} catch (ResourceException e) {
					e.printStackTrace();
				} catch (ScriptException e) {
					e.printStackTrace();
				} catch (Throwable e) {
					e.printStackTrace();
				}
				return null;
			}

		});
        
        try {
            engine.run("contextDestroyed.groovy", binding);
        } catch (ResourceException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch(Throwable e){
            e.printStackTrace();
        }
	}

	public void contextInitialized(ServletContextEvent sce) {
		
	    String[] roots = new String[] {sce.getServletContext().getRealPath("WEB-INF/glue")};
	    try {
	        GroovyScriptEngine engine = new GroovyScriptEngine(roots);
	        sce.getServletContext().setAttribute("glue_groovy_engine", engine);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
		
		final GroovyScriptEngine engine = (GroovyScriptEngine)sce.getServletContext().getAttribute("glue_groovy_engine");
        final Binding binding = new Binding();
        
        binding.setVariable("servletContext", sce.getServletContext());
        binding.setVariable("context", sce.getServletContext());
		binding.setVariable("script", new Object() {
			public Object evaluate(String name) {
				try {
					return engine.run(name, binding);
				} catch (ResourceException e) {
					e.printStackTrace();
				} catch (ScriptException e) {
					e.printStackTrace();
				} catch (Throwable e) {
					e.printStackTrace();
				}
				return null;
			}

		});
        
        try {
            engine.run("contextCreated.groovy", binding);
        } catch (ResourceException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch(Throwable e){
            e.printStackTrace();
        }
	}
}
